package gl.android.biyiqing.fragment;

import gl.App;
import gl.adapter.JsonArrayImageListAdapter;
import gl.android.biyiqing.R;
import gl.android.biyiqing.api.API;
import gl.android.biyiqing.bean.BYQUserInfo;
import gl.android.biyiqing.bean.Result;
import gl.android.biyiqing.competent.ByqAjaxCallProxy;
import gl.android.biyiqing.competent.OnToUserInfoItemClickListener;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.Dateutil;
import gl.uitls.GsonUtils;
import gl.uitls.Tip;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class PartyInfoFragment extends BaseListFragmet {
	// Content View Elements

	// Content View Elements

	// Content View Elements

	String NOTFOUND = "当前没什么内容\n再试一次吧！";
	public static String KEY_PARTYID = "partyid";
	private String partyid;
	private ImageView imageView1;
	private TextView textView1;
	private WebView textView2;
	private ViewSwitcher viewSwitcher;
	private TextView zhuban;
	private TextView yaoqing;
	private TextView lianxifangshi;
	private TextView feiyongshuoming;
	private TextView huodongdiqu;
	private TextView huodongdidian;
	private TextView huodongshijian;
	private TextView jiezhibaoming;
	private TextView liulanrenqi;
	private Button button1;

	// End Of Content View Elements

	private void bindViews() {

		zhuban = (TextView) findViewById(R.id.zhuban);
		yaoqing = (TextView) findViewById(R.id.yaoqing);
		lianxifangshi = (TextView) findViewById(R.id.lianxifangshi);
		feiyongshuoming = (TextView) findViewById(R.id.feiyongshuoming);
		huodongdiqu = (TextView) findViewById(R.id.huodongdiqu);
		huodongdidian = (TextView) findViewById(R.id.huodongdidian);
		huodongshijian = (TextView) findViewById(R.id.huodongshijian);
		jiezhibaoming = (TextView) findViewById(R.id.jiezhibaoming);
		liulanrenqi = (TextView) findViewById(R.id.liulanrenqi);

		textView1 = (TextView) findViewById(R.id.textView1);
		textView2 = (WebView) findViewById(R.id.textView2);
		imageView1 = (ImageView) findViewById(R.id.imageView1);
		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher1);
		button1 = (Button) findViewById(R.id.button1);
		button1.setOnClickListener(signupparty);
		viewSwitcher.setDisplayedChild(0);
		final Button btn_baoming = (Button) rootView.findViewById(R.id.button2);
		btn_baoming.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isShowList) {
					viewSwitcher.setDisplayedChild(0);
					btn_baoming.setText("报名会员");
				}
				else {
					viewSwitcher.setDisplayedChild(1);
					btn_baoming.setText("活动介绍");
				}
				isShowList = !isShowList;

			}
		});
	}

	boolean isShowList = true;

	public PartyInfoFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		partyid = getArguments().getString(KEY_PARTYID);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_partyinfo, container,
				false);
		bindViews();
		initData();
		return rootView;
	}

	private boolean hasSignUp = false;
	String urls[] = new String[] { "CancelParty?partyid=%s&userid=%s",
			"SignupParty?partyid=%s&userid=%s" };
	View.OnClickListener signupparty = new OnClickListener() {
		@Override
		public void onClick(View v) {
			BaseControl.get(API.URL + urls[hasSignUp ? 0 : 1],
					new ByqAjaxCallProxy() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							try {
								Result result = unformat(t);
								// 0表示已加入活动 1表示加入活动失败 2 表示加入活动成功  3表示会员级别不够  4表示人数已满
								if ("0".equals(result.getMsg())) {
									Tip.show(String.format("已经%s活动",
											!hasSignUp ? "加入" : "退出"));
								}
								else if ("1".equals(result.getMsg())) {
									Tip.show(String.format("%s活动失败",
											!hasSignUp ? "加入" : "退出"));
								}
								else if ("2".equals(result.getMsg())) {
									Tip.show(String.format("%s活动成功",
											!hasSignUp ? "加入" : "退出"));
									initData();
								}
								else if ("4".equals(result.getMsg())) {
									Tip.show(String.format("%s活动失败,会员级别不够,请升级会员",
											!hasSignUp ? "加入" : "退出"));
									initData();
								}
								else if ("3".equals(result.getMsg())) {
									Tip.show(String.format("%s活动失败,报名人数已满",
											!hasSignUp ? "加入" : "退出"));
									initData();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}

						}
					}, new Object[] { partyid, getUserID() });

		}
	};

	private void initData() {
		BaseControl.get(API.URL + "GetPartyInfo?partyid=%s",
				new ByqAjaxCallProxy() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							Result result = unformat(t);
							data = t;
							final JSONObject jsonObject = new JSONArray(
									result.data).optJSONObject(0);
							textView1.setText(jsonObject.optString("title"));
							textView1.setTextColor(getResources().getColor(
									R.color.theme));
							textView2.loadDataWithBaseURL(null,jsonObject
									.optString("content"), "text/html", "utf-8",null);
							zhuban.setText(jsonObject.optString("hoster"));
							yaoqing.setText(
									"男:"+ jsonObject.optInt("ivmalenum")+
									" 女:"+ jsonObject.optInt("ivfemalenum")
									);
							lianxifangshi.setText(jsonObject
									.optString("contact"));
							feiyongshuoming.setText(""
									+ jsonObject.optInt("fee"));
							huodongdiqu.setText(BYQUserInfo.getQUYUReadable(
									jsonObject.optInt("provinceid"),
									jsonObject.optInt("cityid")));
							huodongdidian.setText(jsonObject
									.optString("partyaddress"));
							huodongshijian.setText(jsonObject
									.optString("partytime"));
							jiezhibaoming.setText(Dateutil.getTimeString(
									new SimpleDateFormat("yyyy年MM月dd日 HH时"),
									jsonObject.optInt("endsignup") * 1000l));
							liulanrenqi.setText("" + jsonObject.optInt("hits"));

							zhuban.setText(jsonObject.optString("hoster"));
							JSONObject jo;
							jo = new JSONArray(result.data).getJSONObject(0);
							App.mFBitmap.display(imageView1,
									API.IMAGEURL + jo.optString("uploadfiles"));

							String from[] = new String[] { "avatar" };
							initMember(t, from);

							ArrayList<HashMap<String, String>> maps = GsonUtils
									.JSON2MapArrayList(new JSONObject(t)
											.optJSONArray("signup"));
							hasSignUp = false;
							int allowjoin = jsonObject.optInt("allowjoin");
							if (allowjoin==1) {
								button1.setText("报名已结束");
								button1.setEnabled(false);
							}else{
								button1.setText("我要报名");
							}
							for (int i = 0; i < maps.size(); i++) {
								if (maps.get(i)
										.get("userid")
										.equals(UserManger.getInstance().userid)) {
									hasSignUp = true;
									button1.setText("取消报名");
								}
							}
							// initAdapter(getListView(),
							// R.layout.item_grid_simple_image_text,
							// new String[] { "avatar"/*, "qq"*/ }, new int[] {
							// R.id.iv_avator/*, R.id.tv_nick, */},
							// new JSONObject(t).optJSONArray("signup")
							// .toString());
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					public void initMember(String t, String[] from)
							throws JSONException {

						// , "gender"
						final JSONArray memberJsonArray = new JSONObject(t)
								.optJSONArray("signup");
						JSONArray manmemberJsonArray = new JSONArray();
						JSONArray womanmemberJsonArray = new JSONArray();
						int counnt1 = 0;
						int counnt2 = 0;
						for (int i = 0; i < memberJsonArray.length(); i++) {
							if ("1".equals(memberJsonArray.getJSONObject(i)
									.optString("gender"))) {// man
								manmemberJsonArray.put(memberJsonArray
										.getJSONObject(i));
								counnt1++;
							}
							else {
								womanmemberJsonArray.put(memberJsonArray
										.getJSONObject(i));
								counnt2++;
							}
						}
						final TextView tv_nv = (TextView) findViewById(R.id.yibaomingnv);
						final TextView tv_nan = (TextView) findViewById(R.id.yibaomingnan);
						tv_nan.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								findViewById(R.id.list2)
										.setVisibility(
												findViewById(R.id.list2)
														.getVisibility() == View.GONE ? View.VISIBLE
														: View.GONE);

							}
						});
						tv_nv.setOnClickListener(new View.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								findViewById(R.id.list1)
								.setVisibility(
										findViewById(R.id.list1)
										.getVisibility() == View.GONE ? View.VISIBLE
												: View.GONE);
								
							}
						});
						tv_nv.setText(String.format(tv_nv.getText().toString(),
								counnt2));
						tv_nan.setText(String.format(tv_nan.getText()
								.toString(), counnt1));
						((AbsListView) findViewById(R.id.list2))
								.setAdapter(new JsonArrayImageListAdapter(
										getActivity(), manmemberJsonArray
												.toString(),
										R.layout.item_grid_simple_image_text,
										from, new int[] { R.id.iv_avator },
										getOnItemChildViewCilck()));
						((AbsListView) findViewById(R.id.list2))
								.setOnItemClickListener((OnItemClickListener) getOnItemListener(
										from, manmemberJsonArray));

						((AbsListView) findViewById(R.id.list1))
								.setAdapter(new JsonArrayImageListAdapter(
										getActivity(), womanmemberJsonArray
												.toString(),
										R.layout.item_grid_simple_image_text,
										from, new int[] { R.id.iv_avator },
										getOnItemChildViewCilck()));
						((AbsListView) findViewById(R.id.list1))
								.setOnItemClickListener((OnItemClickListener) getOnItemListener(
										from, womanmemberJsonArray));
					}
				}, new Object[] { partyid });
	}

	public Object getOnItemListener(final String[] from, String t)
			throws JSONException {
		return new OnToUserInfoItemClickListener(getActivity(),t, from);
	}
}
